// 引入样式
require("../../assets/css/index.less")
require("./register.less")
require('weui')

const CaptchaMini = require('captcha-mini')
const weui = require('weui.js')

const { ready, getEle, addEvent } = require('../../utils/dom')
const { checkPhone, chackPassword } = require("../../utils/validator")
const { post } = require("../../utils/https")
ready(() => {
    let captcha1 = new CaptchaMini({ fontSize: 40, })
    let code;
    captcha1.draw(getEle("#captcha1"), r => code = r.toUpperCase())

    addEvent("#pwsLogin", () => location.href = 'login.html')

    addEvent("#regBtn", () => {


        if (!checkPhone(getEle("#account").value)) {
            getEle("#err").textContent = "电话号码格式错误"
            return
        }

        if (getEle("#code").value.toUpperCase() != code) {
            getEle("#err").textContent = "验证码错误"
            getEle("#captcha1").click()
            return
        }

        if (!chackPassword(getEle("#password").value)) {
            getEle("#err").textContent = "以字母开头，长度在6~18之间，只能包含字母、数字和下划线"
            return
        }

        if (getEle("#passwordAgain").value !== getEle("#password").value) {
            getEle("#err").textContent = "密码不一致"
            return
        }
        post("/api/user/isExist",
            { account: getEle("#account").value }, res => {
                if (res.errno == 0) {
                    post("/api/user/register",
                        {
                            account: getEle("#account").value,
                            password: getEle("#password").value
                        }, res => {
                            if (res.errno == 0) {
                                weui.toast('注册成功', function () {
                                    location.href = "login.html"
                                })
                            }

                        })
                } else {
                    weui.alert(res.message)
                }
            })


        getEle("#err").textContent = ""
    })

})
